package com.file.parser.socialsecurity;


import com.file.bo.ResponseData;
import com.file.bo.socialsecurity.JiangxiIndividualRecordSheet;
import com.file.bo.socialsecurity.JiangxiInsuranceParticipation;
import com.file.constant.ErrorCode;
import com.file.parser.BasePdfParser;
import com.file.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import technology.tabula.*;
import technology.tabula.detectors.SpreadsheetDetectionAlgorithm;
import technology.tabula.extractors.SpreadsheetExtractionAlgorithm;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class JiangxiSocialSecurityPdfParser extends BasePdfParser {

    public ResponseData<String> parseJiangxiSocialSecurityPdfToJson(String daId, String filePath) {
        log.info("parseJiangxiSocialSecurityPdfToJson started, daId:{}", daId);
        String json = null;

        try {
            if (filePath.contains("cbzm")) {
                JiangxiInsuranceParticipation jiangxiInsuranceParticipation = parseJiangxiInsuranceParticipation(filePath, daId);
                json = JsonUtils.convertObjectToJson(jiangxiInsuranceParticipation);
            } else if (filePath.contains("qyd")) {//NOSONAR
                JiangxiIndividualRecordSheet jiangxiIndividualRecordSheet = parseJiangxiIndividualRecordSheet(filePath);
                json = JsonUtils.convertObjectToJson(jiangxiIndividualRecordSheet);//NOSONAR
            } else {
                log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseJiangxiSocialSecurityPdfToJson failed, new type not supported");
                return new ResponseData<>(null, ErrorCode.FILE_PARSE_EXCEPTION.getCode(), ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
            }
        } catch (Exception e) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseJiangxiSocialSecurityPdfToJson failed", e);
            return new ResponseData<>(null, ErrorCode.FILE_PARSE_EXCEPTION.getCode(), ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseJiangxiSocialSecurityPdfToJson completed, daId:{}", daId);
        return new ResponseData<>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    private JiangxiInsuranceParticipation parseJiangxiInsuranceParticipation(String filePath, String daId) {
        JiangxiInsuranceParticipation jiangxiInsuranceParticipation = parseJiangxiInsuranceParticipationHeader(filePath, daId);
        List<List<String>> rowList = parseFileToRowList(filePath);
//        for (List<String> cellList : rowList) {
//            System.out.println(cellList);
//        }

        parseListToBO(rowList, jiangxiInsuranceParticipation);
        return jiangxiInsuranceParticipation;
    }

    private JiangxiInsuranceParticipation parseJiangxiInsuranceParticipationHeader(String filePath, String daId) { //NOSONAR
        JiangxiInsuranceParticipation jiangxiInsuranceParticipation = new JiangxiInsuranceParticipation();
        String pdfText = getPdfTextByStripper(filePath)
                .replace(System.getProperty("line.separator", "\n"), StringUtils.EMPTY);
//        System.out.println(pdfText);

        String applicationQueryDate = parsePdfHeaderField(pdfText, "申请查询日期|日江西省社会保险个人参保证明") + "日";
        jiangxiInsuranceParticipation.setApplicationQueryDate(applicationQueryDate);

        return  jiangxiInsuranceParticipation;
    }

    private JiangxiIndividualRecordSheet parseJiangxiIndividualRecordSheet(String filePath) { //NOSONAR
        JiangxiIndividualRecordSheet jiangxiIndividualRecordSheet = new JiangxiIndividualRecordSheet();
        return jiangxiIndividualRecordSheet;
    }

    private void parseListToBO(List<List<String>> rowList, JiangxiInsuranceParticipation jiangxiInsuranceParticipation) {
        List<JiangxiInsuranceParticipation.SocialInsurancePaymentDetails> socialInsurancePaymentDetailsList = new ArrayList<>();
        List<JiangxiInsuranceParticipation.CurrentInsuranceStatus> currentInsuranceStatusList = new ArrayList<>();

        String sectionName = "";

        for (int i = 0; i < rowList.size(); i++) {
            List<String> cellList = rowList.get(i);
            if (StringUtils.equals(cellList.get(0), "个人基本信息")) {
                sectionName = "个人基本信息";
                continue;
            } else if (StringUtils.equalsAny(cellList.get(0), "当前参保情况", "个人社保编号") && !StringUtils.equals(sectionName, "社会保险缴费明细")) {
                sectionName = "当前参保情况";
                continue;
            } else if (StringUtils.equalsAny(cellList.get(0), "社会保险缴费明细", "个人社保编号")) {
                sectionName = "社会保险缴费明细";
                continue;
            }
            switch (sectionName) { //NOSONAR
                case "个人基本信息":
                    JiangxiInsuranceParticipation.PersonalBasicInformation personalBasicInformation = new JiangxiInsuranceParticipation.PersonalBasicInformation();
                    personalBasicInformation.setName(cellList.get(1));
                    personalBasicInformation.setGender(cellList.get(3));
                    personalBasicInformation.setIdNo(cellList.get(5));
                    jiangxiInsuranceParticipation.setPersonalBasicInformation(personalBasicInformation);
                    break;
                case "当前参保情况":
                    JiangxiInsuranceParticipation.CurrentInsuranceStatus currentInsuranceStatus = new JiangxiInsuranceParticipation.CurrentInsuranceStatus();
                    currentInsuranceStatus.setPersonalSocialSecurityNumber(cellList.get(0));
                    currentInsuranceStatus.setInsuranceTypeName(cellList.get(1));
                    currentInsuranceStatus.setInsuredStatus(cellList.get(2));
                    currentInsuranceStatus.setInsuredPlace(cellList.get(3));
                    currentInsuranceStatus.setInsuredUnitName(cellList.get(4));
                    currentInsuranceStatusList.add(currentInsuranceStatus);
                    break;
                case "社会保险缴费明细":
                    JiangxiInsuranceParticipation.SocialInsurancePaymentDetails socialInsurancePaymentDetails = new JiangxiInsuranceParticipation.SocialInsurancePaymentDetails();
                    socialInsurancePaymentDetails.setPersonalSocialSecurityNumber(cellList.get(0));
                    socialInsurancePaymentDetails.setInsuranceTypeName(cellList.get(1));
                    socialInsurancePaymentDetails.setPaymentStartAndEndTime(cellList.get(2));
                    socialInsurancePaymentDetails.setMonthlyPaymentBase(cellList.get(3));
                    socialInsurancePaymentDetails.setIsPaymentReceived(cellList.get(4));
                    socialInsurancePaymentDetails.setPaymentUnitName(cellList.get(5));
                    socialInsurancePaymentDetailsList.add(socialInsurancePaymentDetails);
                    break;
            }
        }

        jiangxiInsuranceParticipation.setCurrentInsuranceStatusList(currentInsuranceStatusList);
        jiangxiInsuranceParticipation.setSocialInsurancePaymentDetailsList(socialInsurancePaymentDetailsList);

    }

    private List<List<String>> parseFileToRowList(String filePath) {
        // 1. 读取文件
        File pdf = new File(filePath);

        //页面所有table的记录，每一个元素代表下面一条记录cellList
        List<List<String>> rowList = new ArrayList<>();

        // 2. pdfbox读取PDDocument
        try (PDDocument pdfDocument = PDDocument.load(pdf)) {
            // 3. tabula新建ObjectExtractor和NurminenDetectionAlgorithm，同时准备接收表格Rectangle的结构
            ObjectExtractor objectExtractor = new ObjectExtractor(pdfDocument);
            SpreadsheetDetectionAlgorithm detectionAlgorithm = new SpreadsheetDetectionAlgorithm();
            Map<Integer, List<Rectangle>> pageNumber2RectangleListMap = new HashMap<>();//key为页的序号， value为对应的Rectangle的list

            // 4. 获取每页的PageIterator
            PageIterator pageIterator = objectExtractor.extract();

            // 5. 解析每页的Rectangle
            // 如果单页pdf中有多个Rectangle，则解析出来的List<Rectangle>会有多个对象
            while (pageIterator.hasNext()) {
                Page page = pageIterator.next();
                List<Rectangle> rectangleList = detectionAlgorithm.detect(page);
                if (rectangleList.size() > 0) {
                    pageNumber2RectangleListMap.put(page.getPageNumber(), rectangleList);
                }
            }

            // 6.通过table位置获取表格具体内容
            SpreadsheetExtractionAlgorithm extractionAlgorithm = new SpreadsheetExtractionAlgorithm();

            // 如果单页pdf中有多个表格，则解析出来的List<Rectangle>会有多个对象
            for (Map.Entry<Integer, List<Rectangle>> entry : pageNumber2RectangleListMap.entrySet()) {
                Page page = objectExtractor.extract(entry.getKey());
                Rectangle rectangle = null;

                List<Rectangle> rectangleList = entry.getValue();
                for (Rectangle r : rectangleList) {
                    double rectangleHeight = r.getHeight();
                    if (Double.compare(rectangleHeight, 0) > 0) {
                        rectangle = r;
                        break;
                    }
                }
                if (rectangle == null) {
                    throw new RuntimeException("rectangle is null.");
                }

                if (entry.getKey() > 1) {
                    rectangle.setTop(rectangle.getTop());
                }
                rectangle.setBottom(rectangle.getBottom());
                Page area = page.getArea(rectangle);

                // 如果每页有多个表格，解析每一个table
                List<Table> tableList = extractionAlgorithm.extract(area);
                for (Table table : tableList) {
                    for (int i = 0; i < table.getRowCount(); i++) {
                        List<String> cellList = new ArrayList<>();//一条记录，每个单元格占一个元素
                        for (int j = 0; j < table.getColCount(); j++) {
                            cellList.add(table.getCell(i, j).getText(false));
                        }
                        rowList.add(cellList);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

        return rowList;
    }

    public static void main(String[] args) {
        String filePath = "D:\\data\\file\\socialsecurity\\江西\\江西1\\app-gjzwfw-dzsb_cbzm.pdf";
        JiangxiSocialSecurityPdfParser jiangxiSocialSecurityPdfParser = new JiangxiSocialSecurityPdfParser();
        String json = jiangxiSocialSecurityPdfParser.parseJiangxiSocialSecurityPdfToJson("", filePath).getData();
        System.out.println("----------------------------------------------------------");
        System.out.println(json);
    }

}
